package com.stevenxin.service;

import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.stevenxin.mapper.UsersMapper;
import com.stevenxin.pojo.Users;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class UserServiceImp implements IUserService {

	@Autowired
	UsersMapper usersMapper;
	
	@Autowired
	Sid sid;
	
	@Transactional(propagation=Propagation.SUPPORTS)
	@Override
	public boolean queryUserNameIsExist(String userName) {
		Users u=new Users();
		u.setUsername(userName);
		Users res= usersMapper.selectOne(u);
		return res==null ? false : true;
	}
	
	@Transactional(propagation=Propagation.SUPPORTS)
	@Override
	public Users queryUserForLogin(String username, String password) {
		Example userExample= new Example(Users.class);
		Criteria criteria=userExample.createCriteria();
		criteria.andEqualTo("username", username);
		criteria.andEqualTo("password", password);
		Users res = usersMapper.selectOneByExample(userExample);
		return res;
	}

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public void saveUser(Users user) {
		user.setId(sid.nextShort());
		usersMapper.insert(user);

	}

	@Override
	public void updateUserInfo(Users user) {
		Example userExample= new Example(Users.class);
		Criteria criteria=userExample.createCriteria();
		criteria.andEqualTo("id", user.getId());
		usersMapper.updateByExampleSelective(user, userExample);
		
	}

}
